package com.huluobo.jetpackkotlindemo2006a.room

import android.os.Bundle
import android.util.Log
import androidx.room.Room
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.huluobo.jetpackkotlindemo2006a.MyApplication
import com.huluobo.jetpackkotlindemo2006a.databinding.ActivityRoomBinding
import com.huluobo.jetpackkotlindemo2006a.viewbinding.BaseActivity

/**
 * Created by lc on 2023/2/16.
 */
class RoomActivity : BaseActivity<ActivityRoomBinding>() {
    override fun getViewBinding(): ActivityRoomBinding = ActivityRoomBinding.inflate(layoutInflater)

    //直接在主线程中创建数据库,这种形式小号的资源比较大,不推荐这么去创建
//    var acc
//    accountDb = Room.databaseBuilder(this, AccountDataBase::class.java, "account.db")

    //通过懒加载的模式使用同步处理创建数据库 mode = LazyThreadSafetyMode.SYNCHRONIZED控制懒加载的线程安全
    //allowMainThreadQueries()可以强制数据库查询运行在主线程当中,演示用,公司项目不可以这么做
    //fallbackToDestructiveMigration() 破坏性的重建数据库,会丢失所有的旧数据
    companion object {
        val accountDb by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            Room.databaseBuilder(
                MyApplication.instance.applicationContext,
                AccountDataBase::class.java,
                "account.db"
            ).allowMainThreadQueries()
//                .fallbackToDestructiveMigration()
                .addMigrations(MIGRATION_2_3)
                .build()
        }

        private val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE Account ADD COLUMN _loginIpAddress TEXT NOT NULL DEFAULT ''")
            }
        }

        private val MIGRATION_2_3 = object : Migration(2, 3) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE Account ADD COLUMN _loginAge TEXT NOT NULL DEFAULT ''")
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewBinding.btnSave.setOnClickListener {


            val account = accountDb.accountDAO.findAccountByLoginAccount(getLoginAccount())

            //let 表示判断当前的对象是否为空,如果不为空则走第一个大括号,如果为空,则走:?的大括号
            account?.let {
                Log.i("TagA", "账号:${getLoginAccount()},账号已存在")
                //如果账号存在,密码也相同,不做任何操作,如果不同,则更新密码
                if (it.loginPassword != getLoginPassword()) {
                    //如果账号的密码不同,做更新密码
                    it.loginPassword = getLoginPassword()
                    accountDb.accountDAO.updateAccountBean(it)
                }

            } ?: let {
                Log.i("TagA", "账号:${getLoginAccount()},账号不存在")
                //保存对象信息
                val accountBean = AccountBean(
                    loginPassword = getLoginPassword(),
                    loginAccount = getLoginAccount(),
                    loginIpAddress = "",
                    loginAge = "12"
                )
                accountDb.accountDAO.insertAccount(accountBean)
            }
        }

        mViewBinding.btnQuery.setOnClickListener {
            val list = accountDb.accountDAO.loadAccountList()
            list?.let {
                mViewBinding.tvResult.text = ""
                for (i in it.indices) {
                    mViewBinding.tvResult.append("账号:${it[i].loginAccount}")
                    mViewBinding.tvResult.append("密码:${it[i].loginPassword}")
                    mViewBinding.tvResult.append("年龄:${it[i].loginAge}")
                }
            }
        }

        mViewBinding.btnDelete.setOnClickListener {
            val list = accountDb.accountDAO.loadAccountList()
            list?.let {
                for (i in it.indices) {
                    if (it[i].loginAccount == getLoginAccount()) {
                        accountDb.accountDAO.deleteAccountBean(it[i])
                    }
                }
            }
        }

    }

    private fun getLoginPassword(): String {
        return mViewBinding.edLoginPassword.text.trim().toString()
    }

    private fun getLoginAccount(): String {
        return mViewBinding.edLoginAccount.text.trim().toString()
    }

    fun closeDb() {
        if (accountDb.isOpen) {
            accountDb.close()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        closeDb()
    }
}